package com.group.eams.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group.eams.pojo.dto.UpdateUserRoleDto;
import com.group.eams.pojo.dto.UserLoginDto;
import com.group.eams.pojo.dto.UserQueryDto;
import com.group.eams.pojo.entity.Permission;
import com.group.eams.pojo.entity.User;
import com.group.eams.pojo.vo.UserListVo;
import com.group.eams.service.PermissionService;
import com.group.eams.service.UserService;
import com.group.eams.mapper.UserMapper;
import com.group.exception.CustomerException;
import com.group.result.ResultEnum;
import com.group.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
* @author 恩哲欣
* @description 针对表【user(用户管理)】的数据库操作Service实现
* @createDate 2024-10-29 16:09:34
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    public static final String secret="FCAasvaswqrfqwwrasdASFCVavfvcjkysdgdsgfetgewgweSAGVSDGERsrbnhreyhrghrehgzvazsvswafvwbhnwe";

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionService permissionService;
    @Override
    public Page<UserListVo> findUserByQueryDto(Page page, UserQueryDto userQueryDto) {
        return getBaseMapper().findUserByQueryDto(page,userQueryDto);
    }

    @Override
    public void updateUserRole(UpdateUserRoleDto updateUserRoleDto) {
        User user = userMapper.selectById(updateUserRoleDto.getUserId());
        user.setRoleId(updateUserRoleDto.getRoleId());
        userMapper.updateById(user);
    }

    @Override
    public String login(UserLoginDto userLoginDto) {
        //2.查询用户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getAccount,userLoginDto.getAccount());
        User user = getBaseMapper().selectOne(lambdaQueryWrapper);
        if(user==null){
            throw new CustomerException(ResultEnum.USERNAME_NOT_EMPTY);
        }

        //3.再次加密
        String md5Password = DigestUtil.md5Hex(userLoginDto.getPassword() + user.getSalt());


        //4.对比两次密码是否一致
        if(!user.getPassword().equals(md5Password)){
            throw new CustomerException(ResultEnum.USERNAME_NOT_EMPTY);
        }

        //查询用户对应的权限
        List<Permission> permissionList = permissionService.findPermissionByUserId(user.getId());
        List<String> permissionPermsList = permissionList.stream().map(permission ->
                permission.getTag()).collect(Collectors.toList());

        //5.生成jwt令牌返回给前端
        Map<String,Object> map=new HashMap<>();
        map.put("id",user.getId());
        map.put("permissionPermsList", JsonUtils.objectToJson(permissionPermsList));
        map.put("name",user.getName());
        map.put("account",user.getAccount());
        map.put("sex",user.getSex());
        map.put("image",user.getImage());
        map.put("phone",user.getPhone());
        map.put("email",user.getEmail());
        map.put("birth",user.getBirth());
        map.put("expireTime",System.currentTimeMillis() + 1000 * 60 * 60 * 24);
        String token = JWTUtil.createToken(map, secret.getBytes());

        return token;
    }

    @Override
    public void insertUser(User user) {

        //1.检查工作
        if(user==null){
            throw new CustomerException(ResultEnum.ADMIN_INFO_NOT_EMPTY);
        }
        checkName(user);
        checkAccount(user);
        checkSex(user);
        checkPhone(user);
        checkEmail(user);

        //2.生成盐
        String salt = UUID.randomUUID().toString().replace("-","");

        //3.默认手机号码后六位为密码  密码加密
        String password=user.getPhone().substring(5);

        //4.密码加密
        String md5Password = DigestUtil.md5Hex(password + salt);

        //5.设置盐和密码
        user.setSalt(salt);
        user.setPassword(md5Password);

        //6.保存数据
        getBaseMapper().insert(user);

    }
    public void checkName(User user) {
        //1.判断用户名是否为空
        if(StrUtil.isEmpty(user.getName())){
            throw new CustomerException(ResultEnum.USERNAME_NOT_EMPTY);
        }
        //2.查询账户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getName,user.getName());
        if(getBaseMapper().selectOne(lambdaQueryWrapper)!=null){
            throw new CustomerException(ResultEnum.USERNAME_IS_EXISTS);
        }
    }
    public void checkAccount(User user) {
        //1.判断用户名是否为空
        if(StrUtil.isEmpty(user.getAccount())){
            throw new CustomerException(ResultEnum.PARAM_NULL);
        }
        //2.查询账户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getAccount,user.getAccount());
        if(getBaseMapper().selectOne(lambdaQueryWrapper)!=null){
            throw new CustomerException(ResultEnum.PARAM_NOT_UNIQUE);
        }
    }
    public void checkSex(User user) {
        //1.判断用户名是否为空
        if(user.getSex()==null){
            throw new CustomerException(ResultEnum.PARAM_NULL);
        }
    }
    public void checkPhone(User user) {
        //1.判断用户名是否为空
        if(StrUtil.isEmpty(user.getPhone())){
            throw new CustomerException(ResultEnum.USER_PHONE_NOT_EMPTY);
        }
        //2.查询账户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone,user.getPhone());
        if(getBaseMapper().selectOne(lambdaQueryWrapper)!=null){
            throw new CustomerException(ResultEnum.USER_PHONE_IS_EXISTS);
        }
    }
    public void checkEmail(User user) {
        //1.判断用户名是否为空
        if(StrUtil.isEmpty(user.getEmail())){
            throw new CustomerException(ResultEnum.USER_EMAIL_NOT_EMPTY);
        }
        //2.查询账户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getEmail,user.getEmail());
        if(getBaseMapper().selectOne(lambdaQueryWrapper)!=null){
            throw new CustomerException(ResultEnum.USER_EMAIL_IS_EXISTS);
        }
    }

}
